package top.mcwebsite.playandroid.common.network.impl

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.util.Log

class NetworkBroadcast : BroadcastReceiver() {

    companion object {
        var isWifiAvailable: Boolean? = null

        private const val TAG = "NetworkBroadcast"
    }

    override fun onReceive(context: Context?, intent: Intent) {
        if (WifiManager.WIFI_STATE_CHANGED_ACTION == intent.action) {
            val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0)
            Log.d(TAG, "Wifi state = $wifiState")
            when (wifiState) {
                WifiManager.WIFI_STATE_ENABLING -> {
                    Log.d(TAG, "Wifi state is enabling")
                }
                WifiManager.WIFI_STATE_ENABLED -> {
                    Log.d(TAG, "Wifi state is enabled")
                    isWifiAvailable = isConnectWifi(intent)
                    Log.d(TAG, "Wifi available = $isWifiAvailable")
                }
                WifiManager.WIFI_STATE_DISABLED -> {
                    Log.d(TAG, "Wifi state is disable")
                }
                WifiManager.WIFI_STATE_UNKNOWN -> {
                    Log.d(TAG, "Wifi state is unknown")
                }
            }
            isWifiAvailable = false
        }
    }

    private fun isConnectWifi(intent: Intent): Boolean =
        intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO)?.state == NetworkInfo.State.CONNECTED
}